 package com.zz.config.shiro;

import com.zz.entity.Permission;
import com.zz.entity.Role;
import com.zz.entity.User;
import com.zz.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 自定义授权
     * AuthorizingRealm 授权接口，在该接口会获取权限信息（doGetAuthorizationInfo）和用户信息（doGetAuthenticationInfo）
     * @param principalCollection 权限
     * @return {@link AuthorizationInfo}
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("进入自定义授权方法");
        //获取当前用户身份信息
        String principal = principalCollection.getPrimaryPrincipal().toString();
        //调用接口方法获取用户的角色信息
        List<String> roles = userService.getUserRoleInfo(principal);
        log.info("当前用户角色信息："+roles);
        //调用接口方法获取用户角色的权限信息
        List<String> permissions = userService.getUserPermissionInfo(roles);
        log.info("当前用户权限信息："+permissions);
        //创建对象，存储当前登录的用户的权限和角色
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //存储角色
        info.addRoles(roles);
        //存储权限信息
        info.addStringPermissions(permissions);
        //返回
        return info;
    }

    /**
     * 自定义身份验证
     * AuthenticationToken 身份验证的抽象接口，该接口会返回2个信息，用户信息（Principal）和凭证信息（Credentials）
     * @param token 令牌;
     * @throws AuthenticationException 身份验证异常
     */
    @Override
    protected org.apache.shiro.authc.AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1. 获取用户身份信息
        String name = token.getPrincipal().toString();
        //2. 调用业务层获取用户信息
        User user = userService.getUserInfoByName(name);
        //3. 非空判断,将数据封装返回
        if (user != null) {
            return new SimpleAuthenticationInfo(
                    token.getPrincipal(),
                    user.getPassword(),
                    ByteSource.Util.bytes("salt"),
                    name
            );
        }
        return null;
    }



}

